package com.cypher.encryptionanddecryption.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.cypher.encryptionanddecryption.R;
import com.cypher.encryptionanddecryption.bluetooth.BluetoothGattManager;
import com.cypher.encryptionanddecryption.bluetooth.BluetoothManagerSingleton;

/**
 * 悬浮按钮实现
 * @author: 古霸天
 * @date: 2020/11/4
 */
public class BluetoothTalkFloatingFragment extends Fragment {
    public ImageButton topBtn;
    public ImageButton botBtn;
    public ImageButton clearBtn;
    private BluetoothGattManager gattManager;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_talk_floating, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 获取蓝牙管理类
        gattManager = BluetoothManagerSingleton.getInstance().getBluetoothGattManager();

        //
        topBtn = view.findViewById(R.id.talk_to_top_btn);
        // 按钮设置监听事件，回到列表顶部
        View.OnClickListener topBtnClick = (v) -> {
            if (isGattNotNull()) {
                gattManager.toTopOrBotList("top");
            }
        };
        topBtn.setOnClickListener(topBtnClick);

        botBtn = view.findViewById(R.id.talk_to_bot_btn);
        // 按钮设置监听事件，回到列表底部
        View.OnClickListener botBtnClick = (v) -> {
            if (isGattNotNull()) {
                gattManager.toTopOrBotList("bot");
            }
        };
        botBtn.setOnClickListener(botBtnClick);

        clearBtn = view.findViewById(R.id.talk_clear_btn);
        // 按钮设置监听事件，清空列表
        View.OnClickListener clearBtnClick = (v) -> {
            if (isGattNotNull()) {
                gattManager.clearList();
            }
        };
        clearBtn.setOnClickListener(clearBtnClick);
    }

    /**
     * 判断蓝牙管理类不为空
     * @return
     */
    public boolean isGattNotNull() {
        // 如果为空，先去单例类中获取一次
        if (gattManager == null)
            gattManager = BluetoothManagerSingleton.getInstance().getBluetoothGattManager();
        return gattManager != null;
    }
}
